<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="query.query.partnerName" placeholder="请输入客户名称" clearable @keyup.enter.native="search" />
      <el-select v-model="query.query.state" placeholder="请选择客户状态" clearable>
        <el-option v-for="item in stateList" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="search">
        查询
      </el-button>
      <el-button type="primary" icon="el-icon-plus" @click="dialogVisible = true">
        新增
      </el-button>
      <el-button @click="downloadExport" type="primary" icon="el-icon-download">
        {{ $t("table.export") }}
      </el-button>
    </div>
    <el-table v-loading="loading" :data="tableData" row-key="id" highlight-current-row border
      :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
      <el-table-column prop="partnerName" label="客户名称" />
      <el-table-column prop="partnerCode" label="客户代码" />
      <el-table-column prop="contact" label="联系人" />
      <el-table-column prop="telephone" label="联系方式" />
      <el-table-column prop="address" label="联系地址" />
      <el-table-column label="状态">
        <template slot-scope="{ row }">
          <el-tag :type="row.state == 1 ? 'success' : 'danger'">{{
            row.state == 1 ? "启用" : "禁用"
            }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column width="240px" :label="$t('table.actions')" fixed="right">
        <template slot-scope="{ row, $index }">
          <div>
            <el-button type="primary" size="mini" @click="handleClick(1, row)">编辑</el-button>
            <el-button :type="row.state == 1 ? 'danger' : 'success'" size="mini" @click="handleClick(0, row)">{{
              row.state == 1 ? "禁用" : "启用" }}</el-button>
            <el-button size="mini" type="danger" @click="handleClick(2, row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="form.id ? '编辑' : '新增'" :visible.sync="dialogVisible" @closed="handleClose" :close-on-click-modal="false">
      <el-form :model="form" ref="ruleForm" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="partnerName" :label-width="formLabelWidth">
              <el-input v-model="form.partnerName" autocomplete="off" placeholder="请输入客户名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户代码" prop="partnerCode" :label-width="formLabelWidth">
              <el-input v-model="form.partnerCode" autocomplete="off" placeholder="请输入客户代码"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="付款方式" prop="paymentModeCopy" :label-width="formLabelWidth">
              <el-select style="width: 100%;" v-model="form.paymentModeCopy" multiple collapse-tags
                placeholder="请选择付款方式">
                <el-option v-for="item in payTypes" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contact" :label-width="formLabelWidth">
              <el-input v-model="form.contact" autocomplete="off" placeholder="请输入联系人"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="telephone" :label-width="formLabelWidth">
              <el-input v-model="form.telephone" autocomplete="off" placeholder="请输入联系方式"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系地址" prop="address" :label-width="formLabelWidth">
              <el-input v-model="form.address" autocomplete="off" placeholder="请输入联系地址"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="收款账号名称" prop="bankName" :label-width="formLabelWidth">
              <el-input v-model="form.bankName" autocomplete="off" placeholder="请输入收款账号名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行账号" prop="bankAccount" :label-width="formLabelWidth">
              <el-input v-model="form.bankAccount" autocomplete="off" placeholder="请输入银行账号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" :label-width="formLabelWidth">
              <el-input v-model="form.email" autocomplete="off" placeholder="请输入邮箱" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开户行" prop="beneficiaryAccountName" :label-width="formLabelWidth">
              <el-input v-model="form.beneficiaryAccountName" autocomplete="off" placeholder="请输入开户行"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="送货地址" :label-width="formLabelWidth">
            <el-table :data="form.addressList" row-key="id" highlight-current-row border
              :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
              <el-table-column prop="partnerName" label="客户名称">
                <template slot-scope="{ row, $index }">
                  <el-input v-model="row.partnerName" placeholder="请输入客户名称" clearable />
                </template>
              </el-table-column>
              <el-table-column prop="telephone" label="手机号">
                <template slot-scope="{ row, $index }">
                  <el-input v-model="row.telephone" placeholder="请输入手机号" clearable />
                </template>
              </el-table-column>
              <el-table-column prop="contact" label="联系人">
                <template slot-scope="{ row, $index }">
                  <el-input v-model="row.contact" placeholder="请输入联系人" clearable />
                </template>
              </el-table-column>
              <el-table-column prop="address" label="地址">
                <template slot-scope="{ row, $index }">
                  <el-input v-model="row.address" placeholder="请输入地址" clearable />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template slot-scope="{ row, $index }">
                  <el-button v-if="$index == 0" type="primary" icon="el-icon-circle-plus-outline" @click="addGenerate"
                    circle></el-button>
                  <el-button v-if="$index > 0" type="danger" icon="el-icon-remove-outline" circle
                    @click="minusGenerate($index, row)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="营业执照副本" :label-width="formLabelWidth">
              <el-upload class="elUpload" ref="elUploadRef" drag accept="image/*,application/pdf" :auto-upload="false"
                action="#" :on-change="handleChange" :on-remove="handleRemove" :limit="1">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <div class="el-upload__tip" slot="tip">只能上传jpg/png/pdf文件</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="form.id">
            <el-form-item :label="isPDF ? '副本PDF' : '副本图片'" :label-width="formLabelWidth">
              <el-image v-if="!isPDF" v-loading="!bargainUrl" :src="bargainUrl" :fit="contain"
                :preview-src-list="[bargainUrl]">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
              <el-button v-else type="text" @click="pdfDownload">点击下载</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose; dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sure">确 定</el-button>
      </div>
    </el-dialog>
    <pagination v-show="total > 0" :total="total" :page.sync="query.pageIndex" :limit.sync="query.pageSize"
      @pagination="getInfo" />
  </div>
</template>
<script>
import {
  partnersList,
  partnersAdd,
  partnersDel,
  partnersEnable,
  partnersStop,
  partnersModify,
  partnersExportExcel,
  codePartnersAddressDelete,
  codePartnersDetail
} from "@/api/andonProblemManager";
import { partnersShowImage, partnersDownload } from "@/api/customerforecast";
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { downfile, deepClone } from "@/utils";

const defaultForm = () => {
  return {
    partnerType: "1",
    paymentModeCopy: [],
    addressList: [{}]
  };
};

export default {
  name: "Customerforecast",
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      stateList: [
        {
          label: "启用",
          value: 1
        },
        {
          label: "禁用",
          value: 0
        }
      ],
      dialogVisible: false,
      dialogType: "new",
      total: 0,
      query: {
        pageIndex: 1,
        pageSize: 20,
        query: {
          partnerType: "1"
        }
      },
      form: defaultForm(),
      payTypes: [
        {
          label: "预付",
          value: "0"
        },
        {
          label: "当月结",
          value: "1"
        },
        {
          label: "30天",
          value: "4"
        },
        {
          label: "60天",
          value: "2"
        },
        {
          label: "90天",
          value: "3"
        }
      ],
      formLabelWidth: "110px",
      tableData: [],
      rules: {
        contact: [
          { required: true, message: "请输入联系人", trigger: "blur" }
        ],
        telephone: [
          { required: true, message: "请输入联系方式", trigger: "blur" }
        ],
        partnerName: [
          { required: true, message: "请输入客户名称", trigger: "blur" }
        ],
        partnerCode: [
          { required: true, message: "请输入客户代码", trigger: "blur" }
        ],
        paymentModeCopy: [
          { required: true, message: "请选择付款方式", trigger: "change" }
        ],
        address: [
          { required: true, message: "请输入地址", trigger: "change" }
        ],
        bankName: [
          { required: true, message: "请输入收款账号名称", trigger: "blur" }
        ],
        bankAccount: [
          { required: true, message: "请输入银行账号", trigger: "blur" }
        ],
        beneficiaryAccountName: [
          { required: true, message: "请输入开户行", trigger: "blur" }
        ]
      },
      bargainUrl: "",
      isPDF: false
    };
  },
  mounted() {
    this.getInfo();
  },
  methods: {
    async minusGenerate(index, row) {
      this.$confirm("确认删除?", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        if (row.id) await codePartnersAddressDelete(row.id)
        this.form.addressList.splice(index, 1)
        this.$message({
          type: "success",
          message: "删除成功!"
        });
      })
    },
    addGenerate() {
      const { addressList } = this.form
      if (!addressList[addressList.length - 1].partnerName) {
        this.$message.error('请输入客户名称')
        return
      }
      if (!addressList[addressList.length - 1].telephone) {
        this.$message.error('请输入手机号')
        return
      } else {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
        let str = addressList[addressList.length - 1].telephone
        if (!reg.test(str)) {
          this.$message.error('手机号格式不正确')
          return
        }
      }
      if (!addressList[addressList.length - 1].contact) {
        this.$message.error('请输入联系人')
        return
      }
      if (!addressList[addressList.length - 1].address) {
        this.$message.error('请输入地址')
        return
      }
      this.form.addressList.push({
        partnerName: '',
        telephone: '',
        contact: '',
        address: ''
      })
    },
    async pdfDownload() {
      try {
        await partnersDownload(this.form.id)
      } catch (err) {
        const reader = new FileReader();
        reader.readAsText(err);
        reader.onload = (event) => {
          const resultString = reader.result; // 这里就是转换后的字符串
          if (resultString.includes('code') && resultString.includes('isSuccess')) {
            this.$message.error(JSON.parse(resultString).message)
          } else {
            downfile("营业执照副本.pdf", err);
          }
        }
      }
    },
    async downloadExport() {
      try {
        await partnersExportExcel(this.query.query);
      } catch (err) {
        const reader = new FileReader();
        reader.readAsText(err);
        reader.onload = (event) => {
          const resultString = reader.result; // 这里就是转换后的字符串
          if (resultString.includes('code') && resultString.includes('isSuccess')) {
            this.$message.error(JSON.parse(resultString).message)
          } else {
            downfile("客户管理.xlsx", err);
          }
        }
      }
    },
    handleChange(file, fileList) {
      this.form.bargainFile = file.raw;
    },
    handleRemove() {
      this.form.bargainFile = "";
    },
    handleClose() {
      this.bargainUrl = "";
      this.form = defaultForm();
      this.$refs["ruleForm"].resetFields();
      this.$refs["elUploadRef"].clearFiles();
    },
    async handleClick(val, item) {
      // 0-启禁用；1-编辑；2-删除
      const id = item.id;
      switch (val) {
        case 0:
          const httpFn = item.state == 0 ? partnersEnable : partnersStop;
          httpFn(id).then(res => {
            this.$message.success(item.state == 0 ? "启用成功" : "禁用成功");
            this.getInfo();
          });
          break;
        case 1:
          const paymentModeCopy = item.paymentMode.split(',')
          this.form = deepClone(item)
          this.$set(this.form, 'paymentModeCopy', paymentModeCopy)
          const { addressList } = await codePartnersDetail(item.id)
          if (!addressList || !addressList.length) {
            this.form.addressList = [{}]
          } else {
            this.form.addressList = []
            addressList.forEach(item => {
              this.form.addressList.push({
                id: item.id,
                partnerName: item.partnerName,
                telephone: item.telephone,
                contact: item.contact,
                address: item.address
              })
            })
          }
          this.dialogVisible = true;
          if (item.bargainUrl) {
            if (item.bargainUrl.indexOf('.pdf') > -1) {
              this.isPDF = true
            } else {
              this.isPDF = false
              const data = await partnersShowImage(this.form.id);
              data && (this.bargainUrl = "data:image/png;base64," + data);
            }
          }
          break;
        case 2:
          this.$confirm("确认删除客户?", "警告", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning"
          }).then(async () => {
            partnersDel(id).then(res => {
              this.getInfo();
              this.$message.success("删除成功");
            });
          });
          break;
      }
    },
    // 保存
    async sure() {
      this.$refs["ruleForm"].validate(async valid => {
        if (valid) {
          const httpFn = this.form.id ? partnersModify : partnersAdd;
          const formData = new FormData();
          // 验证文件
          const isValidFile = await this.validateFileBeforeUpload(
            this.form.bargainFile
          );
          const { addressList } = this.form
          if (!addressList[addressList.length - 1].partnerName) {
            this.$message.error('请输入客户名称')
            return
          }
          if (!addressList[addressList.length - 1].telephone) {
            this.$message.error('请输入手机号')
            return
          } else {
            const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
            let str = addressList[addressList.length - 1].telephone
            if (!reg.test(str)) {
              this.$message.error('手机号格式不正确')
              return
            }
          }
          if (!addressList[addressList.length - 1].contact) {
            this.$message.error('请输入联系人')
            return
          }
          if (!addressList[addressList.length - 1].address) {
            this.$message.error('请输入地址')
            return
          }
          // if ((this.form.id && this.form.bargainFile && !isValidFile) || (!this.form.id && !isValidFile)) {
          //   // 如果文件验证失败，则显示错误消息并返回
          //   this.$message.error("上传文件不符合要求，请重新选择！");
          //   return;
          // }
          for (let key in this.form) {
            if (
              key !== "bargainFile" ||
              (key === "bargainFile" && this.form[key] !== null)
            ) {
              if (key === 'paymentModeCopy') {
                const s = new Set(this.form[key])
                if (formData.get('paymentMode')) {
                  formData.set('paymentMode', [...s].join(','))
                } else {
                  formData.append('paymentMode', [...s].join(','))
                }
              } else if (key === 'addressList') {
                this.form[key].forEach((arr, index) => {
                  Object.keys(arr).forEach(k => {
                    formData.append(`addressList[${index}].${k}`, arr[k]);
                  })
                })
              } else {
                formData.append(key, this.form[key]);
              }
            }
          }
          await httpFn(formData);
          this.$message.success(this.form.id ? "编辑成功" : "新建成功");
          this.getInfo();
          this.dialogVisible = false;
          this.form = defaultForm();
        }
      });
    },
    async getInfo() {
      const { records, total } = await partnersList(this.query);
      this.tableData = records;
      this.total = total;
    },
    search() {
      this.query.pageIndex = 1;
      this.getInfo();
    },
    async deletecustomerforecast() {
      this.$confirm("确认删除?", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        await deleteAll();
        this.$message({
          type: "success",
          message: "删除成功!"
        });
      })
    },
    // 上传文件
    uploadActionUrl(item) {
      const fileObj = item.file;
      // FormData 对象
      const form = new FormData();
      // 文件对象
      form.append("file", fileObj);
      // let formTwo = JSON.stringify(form)
      impCustomerForecastData(form).then(response => {
        this.$message.info("文件：" + fileObj.name + "上传成功");
      });
    },
    // 这是一个异步的验证文件方法，它应该返回一个 Promise，该 Promise 解析为 true（如果文件有效）或 false（如果文件无效）
    // 注意：这个方法应该基于 beforeUpload 的逻辑，但可能需要一些调整来适应异步调用
    async validateFileBeforeUpload(file) {
      if (file) {
        try {
          var extension = file.name
            .split(".")
            .pop()
            .toLowerCase();
          const allowedExtensions = ["jpg", "jpeg", "png", "pdf"];
          if (!allowedExtensions.includes(extension)) {
            // this.$message({
            //   message: "上传文件只能是.jpg、.jpeg、.png格式!",
            //   type: "warning"
            // });
            return false;
          }
          // 这里可以添加更多的文件验证逻辑，比如文件大小等
          return true;
        } catch (error) {
          console.error("文件验证出错:", error);
          return false;
        }
      }
    }
  }
};
</script>
